package com.leyou.auth.service.impl;

import com.leyou.auth.constants.JwtConstants;
import com.leyou.auth.constants.RedisConstants;
import com.leyou.auth.dto.Payload;
import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.service.UserAuthService;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.CookieUtils;
import com.leyou.user.client.UserClient;
import com.leyou.user.dto.UserDTO;
import feign.FeignException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author BaiZY on 2020/9/4.
 * @version 1.0
 */
@Service
public class UserAuthServiceImpl implements UserAuthService {
    @Autowired
    private UserClient userClient;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void login(String username, String password, HttpServletResponse response) {
        try {
            //调用远程连接
            UserDTO userDTO = userClient.queryUserByPhoneAndPassword(username, password);

            UserDetail userDetail = UserDetail.of(userDTO.getId().longValue(), userDTO.getUsername());

            //调用JwtUtils的方法
            String jwt = jwtUtils.createJwt(userDetail);

            //将cookie写到浏览器中
            writeCookie(response, jwt, -1);

        } catch (FeignException e) {
            throw new LyException(e.status(), e.getMessage());
        }
    }

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response) {
        //1.获取请求中的cookie
        String jwt = CookieUtils.getCookieValue(request, JwtConstants.COOKIE_NAME);

        //2.校验jwt的有效性
        Payload payload = null;
        try {
            payload = jwtUtils.parseJwt(jwt);
        } catch (Exception e) {
            //3.无效,直接返回
            return;
        }

        //4.有效,删除cookie
        CookieUtils.deleteCookie(JwtConstants.COOKIE_NAME, JwtConstants.DOMAIN, response);

        //5.删除redis中的jti
        Long id = payload.getUserDetail().getId();

        redisTemplate.delete(RedisConstants.JTI_KEY_PREFIX + id);
    }

    //将cookie写入到浏览中
    private void writeCookie(HttpServletResponse response, String info, Integer time) {
        Cookie cookie = new Cookie(JwtConstants.COOKIE_NAME, info);
        cookie.setDomain(JwtConstants.DOMAIN);
        cookie.setHttpOnly(true);
        cookie.setPath("/");
        cookie.setMaxAge(time);
        response.addCookie(cookie);
    }
}
